import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Card, Form, Input, Modal, message, Tooltip, Button } from 'antd';
import StandardTable from '@/components/StandardTable';
import Ellipsis from '@/components/Ellipsis';
import IconButton from '@/components/IconButton';
import Add from './Add';
import get from 'lodash/get';
import styles from './UserGroups.less';
import api from '@/api';

const FormItem = Form.Item;
const { Search } = Input;

@connect(({ loading, usergroups, org }) => ({
  loadingUserGroupsList: loading.effects['usergroups/fetchUserGroupsList'],
  userGroupsList: usergroups.userGroupsList,
  orgTree: org.orgTree,
  deleteLoading: loading.effects['usergroups/deleteUsers'],
  createLoading: loading.effects['usergroups/addUsers']
}))
@Form.create()
class Content extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    selectedRows: [],
    targetKeys: [],
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.currentRootId !== nextProps.currentRootId) {
      this.setState({
        selectedRows: [],
      });
    }
  }

  // 用户组下的用户列表的columns
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '姓名',
      dataIndex: 'fullName',
    },
    {
      title: '账号',
      dataIndex: 'userName',
    },
    {
      title: '组织',
      render: (text, record, index) => {
        return (
          <Ellipsis tooltip length={10} className={styles.ellipsis}>
            {`${(record.orgs || []).map(org => org.shortName)}`}
          </Ellipsis>
        );
      },
    },
    {
      title: '手机',
      dataIndex: 'mobilePhone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      render: (text, record, index) => {
        return (
          <Ellipsis tooltip length={20} className={styles.ellipsis}>
            {text}
          </Ellipsis>
        );
      },
    },
  ];

  calcIndex = index => {
    const { userGroupsList } = this.props;
    let currentPage = get(userGroupsList, 'pagination.currentPage') || 1;
    let pageSize = get(userGroupsList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  // 查询用户组下的用户列表
  searchUserGroupsList = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form, currentRootId } = this.props;
    let queryParams = {
      pageIndex,
      pageSize,
      ...rest,
    };
    dispatch({
      type: 'usergroups/fetchUserGroupsList',
      payload: {
        pathParams: {
          id: currentRootId,
        },
        queryParams: queryParams,
      },
    });
  };

  // 用户组的用户列表的选择
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  // 用户组列表的分页、排序、过滤
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.searchUserGroupsList(params);
    this.setState({
      selectedRows: [],
    });
  };

  // 用户组的用户列表的删除
  deleteUsers = () => {
    const { dispatch, currentRootId, deleteLoading } = this.props;
    if (deleteLoading) return
    const { selectedRows } = this.state;
    Modal.confirm({
      title: '删除',
      content: '确定删除所选用户吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'usergroups/deleteUsers',
          payload: {
            pathParams: {
              id: currentRootId,
            },
            data: selectedRows.map(item => item.id),
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('删除成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUserGroupsList();
          }
        });
      },
    });
  };

  queryOrgTree = () => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'org/queryOrgTree',
    });
  };
  // 添加用户按钮
  addUsers = () => {
    this.setState({
      modalVisible: true,
      targetKeys: [],
    });
    this.queryOrgTree();
  };

  // 校验用户成员是否唯一
  checkUserRoleUnique = async (currentRootId, targetKeys) => {
    if (currentRootId === '_OSS_SYS_FINANCE_INFO_01' || currentRootId === '_OSS_SYS_SERVICE_INFO_01') {
      return []
    }
    let res = await api.usergroups.checkUserRoleUnique({
      pathParams: {
        id: currentRootId,
      },
      data: targetKeys
    })
    if (res.errorCode === 0) {
      return []
    } else {
      let names = this.getDuplicateNames(res.data)
      return names
    }
  }

  // 获取所有重复的用户名
  getDuplicateNames = (users) => {
    let names = []
    users.forEach(item => {
      names.push(`${item.userName}在${item.orgName}中已存在`)
    })
    return names
  }

  // 添加模态框的确定按钮
  okHandle = async () => {
    const { dispatch, currentRootId, createLoading } = this.props;
    const { targetKeys } = this.state;
    let names = await this.checkUserRoleUnique(currentRootId, targetKeys)
    if (names.length) {
      message.destroy()
      message.error(names.join(','))
      return
    }
    if (createLoading) return
    this.setState({
      modalVisible: false,
    });

    if (targetKeys.length) {
      let res = await dispatch({
        type: 'usergroups/addUsers',
        payload: {
          pathParams: {
            id: currentRootId,
          },
          data: targetKeys,
        },
      });
      if (res.errorCode === 0) {
        message.success('添加成功');
        this.searchUserGroupsList();
      }
    }
  };
  // 添加模态框的取消按钮
  handleModalVisible = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleTargetKeysChange = targetKeys => {
    this.setState({
      targetKeys,
    });
  };

  // 新增用户
  renderModalTable = () => {
    const { modalVisible, targetKeys } = this.state;
    const {
      form: { getFieldDecorator },
      orgTree,
      createLoading
    } = this.props;
    return (
      <Modal
        maskClosable={false}
        keyboard={false}
        style={{ minWidth: '920px' }}
        destroyOnClose
        title="添加成员"
        visible={modalVisible}
        confirmLoading={createLoading}
        onOk={this.okHandle}
        onCancel={this.handleModalVisible}
      >
        <Add
          orgTree={orgTree}
          targetKeys={targetKeys}
          onTargetChange={this.handleTargetKeysChange}
        />
      </Modal>
    );
  };
  // 用户列表
  renderUsers = () => {
    const {
      form: { getFieldDecorator, getFieldValue },
      userGroupsList,
      loadingUserGroupsList,
      currentRootId,
      deleteLoading
    } = this.props;
    const { selectedRows, currentStatus } = this.state;
    return (
      <div className={styles.userGroupContent}>
        <div className={styles.tableListForm}>
          {currentRootId && <IconButton title="添加" icon="icon-add" onClick={this.addUsers} />}
          {selectedRows &&
            selectedRows.length > 0 && (
              <IconButton
                title="删除"
                loading={deleteLoading}
                style={{ marginLeft: 10 }}
                icon="icon-delete"
                onClick={this.deleteUsers}
              />
            )}
        </div>
        <StandardTable
          showCheckbox
          rowKey="id"
          selectedRows={selectedRows}
          loading={loadingUserGroupsList}
          data={userGroupsList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  };
  render() {
    return (
      <Card bordered={false}>
        {this.renderUsers()}
        {this.renderModalTable()}
      </Card>
    );
  }
}

export default Content;
